/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.proxy.support;

import com.aduib.boot.common.compiler.JavaPattern;
import com.aduib.boot.common.exception.CommonException;
import com.aduib.boot.common.proxy.MethodInterceptor;
import com.aduib.boot.common.proxy.invocation.ReflectionMethodInvocation;
import com.aduib.boot.common.util.ClassUtils;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.This;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @description: ByteBuddyProxy
 * @author: zzh
 * @date: 2021/10/25 17:16
 */
public class ByteBuddyProxy extends AbstractProxy implements InvocationHandler, Serializable {

  public static final String TAG = "$$ByteBuddyGenerated$$";

  private final boolean enabledPrintClassInfo =
      Boolean.parseBoolean(System.getProperty("aduib.class.enabledPrint", "false"));

  public ByteBuddyProxy(Object targetObject) {
    super(targetObject);
  }

  public ByteBuddyProxy(Class<?> targetClass) {
    super(targetClass);
  }

  @Override
  protected Object doGetProxy(
      ClassLoader classLoader,
      Class<?> targetClass,
      Class<?>[] interfaces,
      Class<?> superClass,
      List<MethodInterceptor> methodInterceptorList) {
    if (superClass == null) {
      superClass = Object.class;
    }
    String className = getClassName(targetClass);
    Method[] declaredMethods = targetClass.getDeclaredMethods();
    final DynamicType.Builder<?> builder =
        new ByteBuddy()
            .with(ClassFileVersion.JAVA_V8)
            .subclass(superClass)
            .name(className)
            .implement(interfaces)
            .method(ElementMatchers.anyOf(declaredMethods))
            .intercept(
                targetClass.isInterface()
                    ? InvocationHandlerAdapter.of(this)
                    : MethodDelegation.to(this));
    DynamicType.Unloaded<?> dynamicType = builder.make();
    //      DynamicType.Loaded<?> dynamicType = builder.make().load(classLoader);
    //      FileUtil.writeFromStream(new ByteArrayInputStream(javaFile),
    // System.getProperty("user.home")+ File.separator+ className + JavaPattern.CLASS_EXTENSION);
    if (enabledPrintClassInfo) {
      try {
        dynamicType.saveIn(
            new File(
                System.getProperty("user.home")
                    + File.separator
                    + className
                    + JavaPattern.CLASS_EXTENSION));
      } catch (IOException ignore) {
      }
    }
    Class<?> loaded = dynamicType.load(classLoader).getLoaded();
    return ClassUtils.newInstance(loaded, constructorArgs);
  }

  private String getClassName(Class<?> targetClass) {
    String name = targetClass.getName();
    if (name.contains(TAG)){
      return name;
    }
    return name + TAG+Math.abs(targetClass.hashCode());
  }

  @RuntimeType
  public Object intercept(@This Object proxy, @Origin Method method, @AllArguments Object[] args)
      throws Exception {
    ReflectionMethodInvocation methodInvocation =
        new ReflectionMethodInvocation(
            proxy, getSourceObject(), method, args, getSourceClass(), getAspectList());
    Object ret = null;
    try {
      ret = methodInvocation.proceed();
    } catch (Throwable e) {
      if (e instanceof Exception) {
        throw new RuntimeException(e);
      }
      if (e instanceof Error) {
        throw new CommonException(e);
      }
    }
    return ret;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    return intercept(proxy, method, args);
  }
}
